package com.tangyee.home_video;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.tangyee.R;

public class HealthyVideoDetails extends AppCompatActivity implements View.OnClickListener{
    private CustomVideoView videoview;
    private TextView type,desc;
    private LinearLayout controllerLayout;
    private ImageView play_controller_img,screen_img,volumn_img,volumn_bg;
    private TextView time_current_tv,time_total_tv;
    private SeekBar play_seek,volumn_seek,volumn_percent;
    public static final int UPDATE_UI=1;
    private int screen_width,screen_height;
    private RelativeLayout videoLayout;
    private AudioManager mAudioManager;
    private Boolean isFullScreen=false;
    private boolean isAdjust=false;
    private int threshold=154;
    private float lastX,lastY;
    private float mBrightness;
    private RelativeLayout progress_layout;
    private ImageView video_back;
    private TextView video_title;
    private TextView videotitle,videotype,videodesc;
    //视频卡顿加载进度条
    private RelativeLayout video_progress;
    //记录视频是否卡顿
    private boolean isVideoStop=false;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_home_videodetails);
        //获取音频服务
        mAudioManager=(AudioManager) getSystemService(AUDIO_SERVICE);
        initUI();
        setPlayerEvent();
        //网络播放
        videoview.setVideoURI(Uri.parse("http://video.ybolo.com/10186/15327a2ebd434beeacad313c4ebceaaa/SD/resource/videos/1_1.mp4"));
        //设置视频播放略缩图

    }

    private void updateTextViewWithTimeFormat(TextView textView,int millisecond){
        int second=millisecond/1000;
        int hh=second/3600;
        int mm=second%3600/60;
        int ss=second%60;
        String str=null;
        if(hh!=0){
            str=String.format("%02d:%02d:%02d",hh,mm,ss);
        }else {
            str=String.format("%02d:%02d",mm,ss);
        }
        textView.setText(str);
    }

    private Handler UIHander=new Handler(){
        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if(msg.what==UPDATE_UI){
                //获取视频当前播放时间
                int currentPosition=videoview.getCurrentPosition();
                //获取视频播放总时间
                int totalduration=videoview.getDuration();
                //格式化视频播放时间
                updateTextViewWithTimeFormat(time_current_tv,currentPosition);
                updateTextViewWithTimeFormat(time_total_tv,totalduration);

                play_seek.setMax(totalduration);
                play_seek.setProgress(currentPosition);
                UIHander.sendEmptyMessageDelayed(UPDATE_UI,500);
            }

        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        UIHander.removeMessages(UPDATE_UI);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setPlayerEvent() {
        //控制视频的播放和暂停
        play_controller_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoview.isPlaying()) {
                    play_controller_img.setImageResource(R.drawable.video_play);
                    //暂停播放
                    videoview.pause();
                    UIHander.removeMessages(UPDATE_UI);
                } else {
                    play_controller_img.setImageResource(R.drawable.video_pause);
                    //继续播放
                    videoview.start();
                    UIHander.sendEmptyMessage(UPDATE_UI);
                }
            }
        });
        //控制快进快退
        play_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                updateTextViewWithTimeFormat(time_current_tv, i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                UIHander.removeMessages(UPDATE_UI);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                //令视频播放进度遵循seekbar停止拖动这一刻的进度
                videoview.seekTo(progress);
                UIHander.sendEmptyMessage(UPDATE_UI);
            }
        });
        //控制音量大小
        volumn_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //设置当前设备音量
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //横竖屏切换
        screen_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isFullScreen) {
                    screen_img.setImageResource(R.drawable.screen);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    screen_img.setImageResource(R.drawable.narrow);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            }
        });
        //设置视频卡顿监听
        videoview.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
                switch (i){
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        //设置屏幕显示信息，开始卡顿
                        video_progress.setVisibility(View.VISIBLE);
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        //设置屏幕显示信息，卡顿结束
                        video_progress.setVisibility(View.GONE);
                        break;
                }
                return true;
            }
        });
        //控制VideoView的手势事件
        videoview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        lastX=motionEvent.getX();
                        lastY=motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float endX=motionEvent.getX();
                        float endY=motionEvent.getY();
                        float detlaX = lastX-endX;
                        float detlaY = lastY-endY;
                        float absdetlaX = Math.abs(detlaX);
                        float absdetlaY = Math.abs(detlaY);
                        if (absdetlaX > threshold && absdetlaY > threshold) {
                            if (absdetlaX < absdetlaY) {
                                isAdjust = true;
                            } else {
                                isAdjust = false;
                            }
                        } else if (absdetlaX < threshold && absdetlaY > threshold) {
                            isAdjust = true;
                        } else if (absdetlaX > threshold && absdetlaY < threshold) {
                            isAdjust = false;
                        }
                        Log.d("合法检验：","手势"+isAdjust);
                        if (isAdjust) {
                            //判断好当前手势事件已经合法的前提下，去区分此时手势应该调节亮度还是调节音量
                            if (endX< getResources().getDisplayMetrics().widthPixels / 2) {
                                //调节亮度
                                if (detlaY > 0) {
                                    //降低亮度
                                    Log.d("调试亮度","降低亮度");
                                } else {
                                    //升高亮度
                                    Log.d("调试亮度","升高亮度");
                                }
                                if(absdetlaX!=0||absdetlaY!=0){
                                    if(progress_layout.getVisibility()==View.GONE){
                                        progress_layout.setVisibility(View.VISIBLE);
                                    }
                                }
                                changeBrightness(detlaY);
                            } else {
                                //调节音量
                                if (detlaY > 0) {
                                    //减小音量
                                    Log.d("调试音量","减小音量");
                                } else {
                                    //增大音量
                                    Log.d("调试音量","增大音量");
                                }
                                if(absdetlaX!=0||absdetlaY!=0){
                                    if(progress_layout.getVisibility()==View.GONE){
                                        progress_layout.setVisibility(View.VISIBLE);
                                    }
                                }
                                changeVolumn(detlaY);
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        progress_layout.setVisibility(View.GONE);
                        break;
                }
                return true;
            }
        });
    }

    private void changeVolumn(float detlaY){
        int max=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current=mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int index=(int)(detlaY/screen_height*max);
        int volumn=Math.max(current+index,0);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,volumn,0);

        volumn_bg.setImageResource(R.drawable.sound);
        volumn_percent.setProgress(volumn);
        volumn_seek.setProgress(volumn);
    }

    private void changeBrightness(float detlaY){
        WindowManager.LayoutParams atrributes=getWindow().getAttributes();
        mBrightness=atrributes.screenBrightness;
        float index=detlaY/screen_height/6;
        mBrightness+=index;
        if(mBrightness>1.0f){
            mBrightness=1.0f;
        }
        if(mBrightness<0.01f){
            mBrightness=0.01f;
        }
        atrributes.screenBrightness=mBrightness;

        volumn_bg.setImageResource(R.drawable.bright);
        volumn_percent.setProgress((int)(100*mBrightness));
        getWindow().setAttributes(atrributes);
    }

    public void initUI(){
        videoview=(CustomVideoView) findViewById(R.id.videoView);
        controllerLayout=(LinearLayout)findViewById(R.id.controllerbar_layout);
        play_controller_img=(ImageView)findViewById(R.id.pause_img);
        screen_img=(ImageView)findViewById(R.id.screen_img);
        screen_img.setImageResource(R.drawable.screen);
        time_current_tv=(TextView)findViewById(R.id.time_current_tv);
        time_total_tv=(TextView)findViewById(R.id.time_total_tv);
        play_seek=(SeekBar) findViewById(R.id.play_seekbar);
        volumn_seek=(SeekBar)findViewById(R.id.volumn_seekbar);
        videoLayout=(RelativeLayout)findViewById(R.id.videoLayout);
        volumn_img=(ImageView)findViewById(R.id.volumn_img);
        volumn_bg=(ImageView)findViewById(R.id.volumn_bg);
        volumn_percent=(SeekBar) findViewById(R.id.volumn_percent);
        progress_layout=(RelativeLayout)findViewById(R.id.progress_layout);
        video_back=(ImageView)findViewById(R.id.iv_video_back_img);
        video_back.setOnClickListener(this);
        video_title=(TextView)findViewById(R.id.tv_video_title);
        video_title.setText(getIntent().getExtras().get("title").toString());
        videotitle=(TextView)findViewById(R.id.video_title_tv);
        videotitle.setText(getIntent().getExtras().get("title").toString());
        videotype=(TextView)findViewById(R.id.video_type_tv);
        String type=getIntent().getExtras().get("type").toString();
        videotype.setText(type.substring(5,type.length()));
        videodesc=(TextView)findViewById(R.id.video_desc_tv);
        String desc=getIntent().getExtras().get("desc").toString();
        videodesc.setText(desc.substring(5,desc.length()));
        video_progress=(RelativeLayout)findViewById(R.id.video_progress);
        screen_width=getResources().getDisplayMetrics().widthPixels;
        screen_height=getResources().getDisplayMetrics().heightPixels;
        //当前设备最大音量
        int streamMaxVolumn=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //获取设备当前音量
        int streamVolumn=mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        volumn_seek.setMax(streamMaxVolumn);
        volumn_seek.setProgress(streamVolumn);
        volumn_percent.setMax(streamMaxVolumn);
        volumn_percent.setProgress(streamVolumn);
    }

    private void setVideoviewScale(int width,int height){
        ViewGroup.LayoutParams layoutParams=videoview.getLayoutParams();
        layoutParams.width=width;
        layoutParams.height=height;
        videoview.setLayoutParams(layoutParams);

        ViewGroup.LayoutParams layoutParams1=videoLayout.getLayoutParams();
        layoutParams1.width=width;
        layoutParams1.height=height;
        videoLayout.setLayoutParams(layoutParams1);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_video_back_img:
                if(isFullScreen){
                    screen_img.setImageResource(R.drawable.screen);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }else{
                    finish();
                }
                break;
        }
    }

    //监听屏幕方向的改变
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //当屏幕方向为横屏时
        if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
            setVideoviewScale(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
            volumn_img.setVisibility(View.VISIBLE);
            volumn_seek.setVisibility(View.VISIBLE);
            isFullScreen=true;
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        //当屏幕方向为竖屏时
        else {
            setVideoviewScale(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(HealthyVideoDetails.this,240));
            volumn_img.setVisibility(View.GONE);
            volumn_seek.setVisibility(View.GONE);
            isFullScreen=false;
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
